<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Main extends Controller {

	public function action_index()
	{
		$aConfig = kohana::$config->load('main');
		$this->response->body(View::factory('main', array_merge($aConfig->as_array(), array(
			'app' => array(
				'version' => '1.05',
				'title' => $aConfig->get('title'),
				'config' => array(
					'defaultTemplate' => View::factory('default-template')->render(),
					'zb_link' => $aConfig->get('zb_link'),
				),
			),
		))));
	}
	
	public function action_manage()
	{
		$aResponse = array();
		$sRequestType = $this->request->method();
		if ($sRequestType === Request::POST) {
			$sConfigFolder = $this->request->post('type').'s_folder';
			$sPath = DOCROOT.Kohana::$config->load('main.'.$sConfigFolder).DIRECTORY_SEPARATOR.
				str_replace('.', DIRECTORY_SEPARATOR, $this->request->post('ns'));
			$sDir = pathinfo($sPath, PATHINFO_DIRNAME);
			switch ($this->request->post('operation')) {
			case 'delete':
			if (file_exists($sPath.'.json') && is_file($sPath.'.json')) {
				$bReturn = @unlink($sPath.'.json');
				if ($bReturn === false) {
					$aResponse['error'] = 'Access denied';
					break;
				}
				if ($this->request->post('type') === 'project') {
					@unlink($sPath.'.tpl.json');
					@unlink($sPath.'.js');
				}
				@rmdir($sDir);
				$aResponse['result'] = ucwords($this->request->post('type')).' deleted';
			}
			else {
				$aResponse['error'] = 'File not found';
			}
			break;
			case 'new':
			case 'edit':
			if (file_exists($sPath.'.json') && is_file($sPath.'.json') &&
				($this->request->post('operation') === 'new' || $this->request->post('old_ns') !== $this->request->post('ns'))) {
				$aResponse['error'] = 'A '.$this->request->post('type').' with the same namespace already exists';
				break;
			}
			case 'save':
			case 'save_js':
			if (!file_exists($sDir) || !is_dir($sDir)) {
				@mkdir($sDir, 0777, true);
			}
			if ($this->request->post('js')) {
				@file_put_contents($sPath.'.js', $this->request->post('js'));
			}
			if ($this->request->post('json')) {
				$bReturn = @file_put_contents($sPath.'.json', $this->request->post('json'));
				if ($bReturn === false) {
					$aResponse['error'] = 'Access denied';
					break;
				}
			}
				if ($this->request->post('type') === 'project' && $this->request->post('template')) {
					@file_put_contents($sPath.'.tpl.json', $this->request->post('template'));
				}
				$aResponse['result'] = 'New file saved';
			break;
			default:
				$aResponse['error'] = 'Invalid operation.';
			}
		}
		if ($sRequestType === Request::GET) {
			$sConfigFolder = $this->request->query('type').'s_folder';
			$sPath = DOCROOT.Kohana::$config->load('main.'.$sConfigFolder);
			switch ($this->request->query('operation')) {
			case 'browse':
				$aList = $this->scanDir($sPath, 'json');
				asort($aList);
				foreach ($aList as $sFile) {
					$sTitle = '';
					$oFile = @fopen($sFile, 'rb');
					if ($oFile) {
						$sTitle = fread($oFile, 512);
						fclose($oFile);
						$iStart = strpos($sTitle, 'title":"') + 8;
						$iEnd = strpos($sTitle, '",', $iStart + 8);
						$sTitle = stripslashes(substr($sTitle,$iStart, $iEnd - $iStart));
						//$sTitle = $iStart.':'.$iEnd; 
					}
					$aResponse['result'][] = array(
						pathinfo(str_replace(DIRECTORY_SEPARATOR, '.', substr($sFile, strlen($sPath) + 1)), PATHINFO_FILENAME),
						$sTitle
				);
				}
			break;
			case 'open':
				$sPath = $sPath.DIRECTORY_SEPARATOR.str_replace('.', DIRECTORY_SEPARATOR, $this->request->query('ns'));
				if (file_exists($sPath.'.json')) {
					$this->response->body('{"result":'.@file_get_contents($sPath.'.json').'}');
					return;
				}
				else {
					$aResponse['error'] = ucwords($this->request->query('type')).' not found';
				}
			break;
			case 'test':
				$sPath = $sPath.DIRECTORY_SEPARATOR.str_replace('.', DIRECTORY_SEPARATOR, $this->request->query('ns'));
				if (file_exists($sPath.'.tpl.json')) {
					$this->response->body($this->generateTestPage(@file_get_contents($sPath.'.tpl.json'), $this->request->query('version')));
					$this->response->headers('cache-control', 'publc; max-age=3600');
				}
				else {
					$this->response->body('Template '.$this->request->query('ns').' not found.');
				}
			return;
			default:
				$aResponse['error'] = 'Invalid operation.';
			}
		}
		$this->response->body(json_encode($aResponse));
	}
	
	protected function scanDir($sPath, $sExt = '*')
	{
		$aScan = array();
		$aList = @scandir($sPath);
		if (empty($aList)) {
			return $aScan;
		}
		foreach($aList as $sItem) { 
			if($sItem !== '.' && $sItem !== '..') {
				$sFile = $sPath.DIRECTORY_SEPARATOR.$sItem;
				if (is_dir($sFile)) {
					$aScan = array_merge($aScan, $this->scanDir($sFile, $sExt));
				}
				elseif ($sExt === '*' || substr($sItem, strpos($sItem.'.', '.') + 1) === $sExt) {
					$aScan[] = $sFile;
				}
			}
		}
		return $aScan;
	}

	protected function generateTestPage($sJson, $sVersion = null)
	{
		$aInfo = @json_decode($sJson, true);
		if (!is_array($aInfo)) { return ''; }
		if (!$sVersion) { $sVersion = $aInfo['version']; }
		$sTemplate = $aInfo['template'];
		unset($aInfo['template']);
		$aInfo = array_map('htmlspecialchars', $aInfo);
		$aInfo['project_script'] = View::factory('project-script', $aInfo);
		$aInfo['jul_script'] = (string)Assets::factory('jul')->js(Kohana::$config->load('main.jul_root').'jul.js');
		//$aInfo['project_script'] = HTML::script(str_replace("\\", '/',  Kohana::$config->load('main.projects_folder')).
		//	'/'.str_replace('.', '/', $aInfo['ns']).'.js?v='.$sVersion);
		$aKeys = array_keys($aInfo);
		foreach ($aKeys as &$sKey) {
			$sKey = strpos($sKey, '_') === false ? '{project_'.$sKey.'}' : '{'.$sKey.'}';
		}
		return str_replace($aKeys, array_values($aInfo), $sTemplate);
	}

} // End Main
